package by.bucha.tabnavigationproject.tabsframework;

import java.util.Stack;

import by.bucha.tabnavigationproject.R;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;

public class TabInfo {

	private AbstractTabActivity mAbstractTabActivity;

	Stack<Fragment> mTabFragments;
	Integer mTag;

	public TabInfo(AbstractTabActivity abstractTabActivity) {
		mAbstractTabActivity = abstractTabActivity;
		mTabFragments = new Stack<Fragment>();
	}

	protected void attachFragment(FragmentTransaction ft, Fragment fragment) {
		Log.d(AbstractTabActivity.TAG, "Attach Fragment "
				+ fragment.getClass().getName());
		if (mAbstractTabActivity.mFragmentsWasAdded.contains(fragment)) {
			Log.d(AbstractTabActivity.TAG, "Fragment exist,just attach it ");
			ft.attach(fragment);
		} else {
			Log.d(AbstractTabActivity.TAG,
					"AddingFragment into FragmentTransaction");
			ft.add(R.id.fragment_container, fragment, String.valueOf(mTag));
			mAbstractTabActivity.mFragmentsWasAdded.add(fragment);
		}
	}

	protected void detachFragment(FragmentTransaction ft, Fragment fragment) {
		if (!fragment.isDetached()) {
			Log.d(AbstractTabActivity.TAG, "Detaching fragment"
					+ fragment.getClass().getName());
			ft.detach(fragment);
		}
	}

	public void onTabSelected(FragmentTransaction ft) {
		attachFragment(ft, mTabFragments.peek());
	}

	public void onTabUnselected(FragmentTransaction ft) {
		detachFragment(ft, mTabFragments.peek());
	}

	public void onTabReselected(FragmentTransaction ft) {

	}

}
